define(function(require, exports) {
	var $ = require('jquery');
	var pubjs = require('pubjs');
	var util = require('util');
	var view = require('@base/view');
	var common = require('@base/common/base');
	var protocolReg = /^https?:\/\/.*/;

	function completionProtocol(url) {
		if (!protocolReg.test(url)) {
			url = 'http://' + url;
		}
		return url;
	}

	// 兴趣网站dashboard模块
	var Base = view.container.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'class': 'M-hotsite',
				'url': '',
				'param': null,
				'auto_load': true,
				"reqType": "ajax",		     // 默认通信方式使用ajax，可选websocket
				"reqMethod":"get",		     // 数据获取方式
				'emptyText': LANG("无数据"),  // 无数据提示

				'barHeight': 32,             // 单个bar高度
				'barColor': ['#a1b6be', '#D1DBDF', '#EAEDF1'],       // bar颜色
				'textColor': '#777',         // 文字颜色

				'xField': {                  // 轴左侧文字字段 可以为字符串
					'field': 'value',
					'format': null,
					'extra': null
				},

				'yField': {          // 轴右侧数据字段, 可以为字符串
					'field': 'value',
					'format': null
				}
			});

			this.Super('init', arguments);
		},
		afterBuild: function() {
			var c = this.getConfig();
			this.append(
				[
					'<div class="M-hotsiteMessage" />',
					'<div class="M-hotsiteMain" >',
						'<div class="M-hotsiteLeft"/>',
						'<div class="M-hotsiteRight"/>',
					'</div>'
				].join('')
			);

			this.$doms = {
				message: this.find('.M-hotsiteMessage'),
				main: this.find('.M-hotsiteMain'),
				left: this.find('.M-hotsiteLeft'),
				right: this.find('.M-hotsiteRight')
			}

			this.reset();

			if (c.auto_load && c.url) {
				this.load();
			}
		},
		reset: function() {
			this.$data = null;
			this.$items = [];
			//this.$doms.main.empty();
			this.$doms.left.empty();
			this.$doms.right.empty();
			this.hideMessage();
			return this;
		},
		setParam: function(param, replace) {
			var c = this.getConfig();
			c.param = replace ? param : util.extend(c.param, param);
			return this;
		},
		load: function() {
			var c = this.getConfig();
			if (c.url) {
				this.toggleLoading(1);
				switch(c.reqType){
					case 'ajax':
						pubjs.data[c.reqMethod](c.url, c.param, this, 'onData');
					break;
					case 'websocket':
						pubjs.mc.send(c.url, c.param, this.onData.bind(this));
					break;
				}
			}

			return this;
		},
		onData: function(err, data) {
			this.toggleLoading(0);

			if (err) {
				return pubjs.alert(err.message);
			}

			this.setData(data || {});
		},
		getData: function() {
			return this.$data;
		},
		setData: function(data) {
			this.reset();

			this.$data = data;
			data = data && data.items || [];

			var c = this.getConfig();
			var doms = this.$doms;

			var xField = c.xField;
			var yField = c.yField;
			yField = util.isArray(yField) ? yField[0] : yField;
			var xFieldKey = util.isString(xField) ? xField : xField.field;
			var yFieldKey = util.isString(yField) ? yField : yField.field;

			// 最大值
			var maxValue;
			// 总个数
			var total = data.length;

			util.each(data.sort(function(a, b) {
				return -a[yFieldKey] + b[yFieldKey];
			}), function(item, index) {
				// 一半在左，一半在右
				var container = index >= total / 2 ? doms.right : doms.left;
				var xValue = item[xFieldKey];
				var yValue = item[yFieldKey];

				var percent = 0;
				var highlight = false;

				// 已经排序，所以第一个值就是分母
				if (index === 0) {
					highlight = true;
					maxValue = yValue;
				}

				percent = Math.round(yValue/maxValue * 100) || 0;
				percent += '%';

				if (util.isFunc(xField.format)) {
					xValue = xField.format.call(this, xValue, item, c) || '-';
				}

				if (util.isFunc(yField.format)) {
					yValue = yField.format.call(this, yValue, item, c) || '-';
				}

				var elm = $([
					'<div class="M-hotsiteItem">',
						'<div class="M-hotsiteItemSerial">' + (this.$items.length + 1) + '.</div>',
						'<div class="M-hotsiteItemBar">',
							'<div class="M-hotsiteItemContent">',
								'<a class="M-hotsiteItemXValue" title="' + (xValue + (xField.extra ? '\n' + item[xField.extra] : ''))  + '"  href="' + completionProtocol(xValue) + '" target="_blank">',
									xValue,
								'</a>',
								'<div class="M-hotsiteItemYValue">' + yValue + '</div>',
							'</div>',
							'<div class="M-hotsiteItemPercent"></div>',
						'</div>',
					'</div>'
				].join('')).appendTo(container);

				elm.css({
					'color': c.textColor,
					'height': c.barHeight + 'px',
					'line-height': c.barHeight + 'px'
				});
				elm.find('.M-hotsiteItemBar').css('background', c.barColor[2]);

				var percentElm = elm.find('.M-hotsiteItemPercent');
				percentElm.css('background', highlight ? c.barColor[0] : c.barColor[1]);
				// 动画
				percentElm.width(percent);

				this.$items.push({
					elm: elm,
					item: item
				});
			}, this);

			return this;
		},
		/**
		 * 切换加载遮罩显示状态
		 * @param  {Boolean}  status  显示状态
		 * @return {Object}           模块实例
		 */
		toggleLoading: function(status) {
			var cs = this.$;
			if (!cs || !cs.loading) {
				this.create(
					"loading"
					,common.loadingMask
					,{
						"target": this.getDOM(),
						"offset_y": 10
					}
				);
			}

			this.$.loading[status ? 'show' : 'hide']();
			return this;
		},
		hideMessage: function() {
			this.$doms.message.hide();
			return this;
		},
		showMessage: function(msg) {
			this.$doms.message.html(msg).show();
			return this;
		}
	});
	exports.base = Base;
});